<template>
  <div class="tit01">审计专项模型分布</div>
  <div class="">
    <div style="width: 100%; height: 200px" ref="modelChart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { queuedFetch } from '../utils/queuedRequest.js'

const modelChart = ref(null)
let modelChartInstance = null

const apiUrl = '/coolv/edatasource/jdbcmgr.do'

// 获取模型分布数据
const loadModelData = async () => {
  const sql = `
SELECT a1.DATE,a2.NAME,count(*) NUM FROM (
	SELECT to_char(YEAR(t1.CREATE_DATE)) DATE,t2.VALUE FROM T_SQL_MODEL t1,T_SQLMODEL_TAG t2 
	WHERE t1.id = t2.id
	AND t1.STATUS = '2'
	UNION ALL 
	SELECT to_char(YEAR(t1.CREATE_DATE)) DATE,t2.VALUE FROM T_DAP_MODEL t1,T_DAP_TAG t2 
	WHERE t1.id = t2.id
	AND t1.STATUS = '2'
	UNION ALL 
	SELECT '全部',t2.VALUE FROM T_SQL_MODEL t1,T_SQLMODEL_TAG t2 
	WHERE t1.id = t2.id
	AND t1.STATUS = '2'
	UNION ALL 
	SELECT '全部',t2.VALUE FROM T_DAP_MODEL t1,T_DAP_TAG t2 
	WHERE t1.id = t2.id
	AND t1.STATUS = '2'
) a1
JOIN (
	SELECT DISTINCT t2.ID,t2.NAME FROM T_TAG_PERMISS_ROLE t1
	JOIN (SELECT ID, NAME, TAG FROM T_TAG_TREE WHERE TAG = (SELECT ID FROM  T_TAG WHERE NAME = '模型分类')) t2
	ON t1.ID = t2.ID
	WHERE t1.TYPE = 1 
) a2
ON a1.VALUE = a2.id
WHERE a2.NAME <> ''
GROUP BY a1."DATE",a2.NAME
ORDER BY a1."DATE" DESC,count(*) DESC 
  `

  // SQL编码：与 amsedb 数据源保持一致
  // 1. URL编码
  let encodedSql = encodeURIComponent(sql)
  // 2. Base64编码
  encodedSql = btoa(encodedSql)

  const formBody = new URLSearchParams()
  formBody.set('action', 'exesql')
  formBody.set('jdbcName', 'DB2')
  formBody.set('enc', 'true')
  formBody.set('sql', encodedSql)
  formBody.set('pageIndex', 'undefined')
  formBody.set('pageSize', '100')
  formBody.set('isSys', 'false')

  console.debug('[ModelDistribution] 请求模型分布数据...')

  try {
    // 使用队列化请求
    const res = await queuedFetch(apiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
      body: formBody.toString()
    }, {
      name: '模型分布数据',
      priority: 2
    })
    const data = await res.json()

    console.log('[ModelDistribution] API响应:', data)

    if (data && Array.isArray(data.datas) && data.datas.length > 0) {
      // 只取类别是"全部"的数据
      const allData = data.datas.filter(row => row[0] === '全部')
      
      console.log('[ModelDistribution] 过滤后的数据:', allData)
      
      // 转换数据格式并按数量排序
      let modelData = allData.map(row => ({
        name: row[1] || '未知',
        value: Number(row[2]) || 0
      })).sort((a, b) => b.value - a.value) // 按数量降序排序
      
      console.log('[ModelDistribution] 排序后的数据:', modelData)
      
      // 只取前10个，其余归为"其他"
      if (modelData.length > 10) {
        const top10 = modelData.slice(0, 10)
        const others = modelData.slice(10)
        const othersSum = others.reduce((sum, item) => sum + item.value, 0)
        
        if (othersSum > 0) {
          top10.push({
            name: '其他',
            value: othersSum,
            isOther: true,
            otherCount: others.length // 记录其他类别包含的模型数量
          })
        }
        
        modelData = top10
        console.log('[ModelDistribution] 合并后的数据(前10+其他):', modelData)
      }
      
      console.log('[ModelDistribution] 最终数据:', modelData)
      updateChart(modelData)
    } else {
      console.warn('[ModelDistribution] 未获取到数据，使用兜底数据')
      // 使用兜底数据
      const defaultData = [
        { name: '信贷风险', value: 15 },
        { name: '市场风险', value: 8 },
        { name: '操作风险', value: 12 },
        { name: '合规风险', value: 10 },
        { name: '战略风险', value: 6 }
      ]
      updateChart(defaultData)
    }
  } catch (error) {
    console.error('[ModelDistribution] 加载数据失败:', error)
    // 使用兜底数据
    const defaultData = [
      { name: '信贷风险', value: 15 },
      { name: '市场风险', value: 8 },
      { name: '操作风险', value: 12 },
      { name: '合规风险', value: 10 },
      { name: '战略风险', value: 6 }
    ]
    updateChart(defaultData)
  }
}

// 更新图表
const updateChart = (data) => {
  if (!modelChartInstance) return
  
  const option = {
    color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC'],
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#29D9D5',
      borderWidth: 1,
      textStyle: { color: '#fff', fontSize: 13, fontWeight: 'normal' },
      padding: [10, 15],
      extraCssText: 'box-shadow: 0 0 20px rgba(41, 217, 213, 0.5); border-radius: 8px;',
      confine: true,
      formatter: (params) => {
        const total = data.reduce((sum, item) => sum + item.value, 0)
        const percent = total ? ((params.value / total) * 100).toFixed(1) : 0
        
        // 检查是否是"其他"类别
        const isOther = params.data.isOther
        const otherCount = params.data.otherCount
        
        let content = `<div style="color:#fff;">
          <div style="font-weight:bold;margin-bottom:5px;color:#29D9D5;">${params.name}</div>
          <div>模型数量：${params.value} 个</div>
          <div>占比：${percent}%</div>`
        
        if (isOther && otherCount) {
          content += `<div style="margin-top:5px;opacity:0.8;">包含 ${otherCount} 个类别</div>`
        }
        
        content += `</div>`
        
        return content
      }
    },
    legend: {
      show: false
    },
    series: [{
      name: '模型分布',
      type: 'pie',
      radius: ['40%', '65%'], // 圆环样式
      center: ['50%', '38%'], // 往上移动
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 0,
        borderColor: 'transparent',
        borderWidth: 0,
        shadowBlur: 6,
        shadowColor: 'rgba(0, 0, 0, 0.2)'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 15,
          shadowOffsetX: 0,
          shadowColor: 'rgba(41, 217, 213, 0.4)',
          borderWidth: 0,
          borderColor: 'transparent'
        },
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        },
        scale: true,
        scaleSize: 10
      },
      label: {
        show: true,
        position: 'outside',
        color: '#fff',
        fontSize: 11,
        fontWeight: 'bold',
        formatter: '{b}\n{d}%'
      },
      labelLine: {
        show: true,
        length: 10,
        length2: 8,
        lineStyle: { 
          color: 'rgba(255, 255, 255, 0.5)',
          width: 1
        },
        smooth: 0.3
      },
      data: data
    }]
  }
  
  modelChartInstance.setOption(option)
}

// 初始化图表
const initChart = () => {
  if (modelChart.value) {
    modelChartInstance = echarts.init(modelChart.value)
    loadModelData()
  }
}

onMounted(() => {
  initChart()
})

onUnmounted(() => {
  if (modelChartInstance) {
    modelChartInstance.dispose()
  }
})
</script>
